package com.genpact.email;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.search.FromTerm;
import javax.mail.search.SubjectTerm;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class MailUitls {
	/**
	 * mail.smtp=58.2.221.2 mail.username=800021189 mail.password=G@28032008t
	 * mail.sender=workflow-center.china@genpact.com mail.smtp.auth=true
	 */

	// smtp服务器
	private static String HOSTNAME = "58.2.221.2";
	private static String USERNAME = "800021189";
	private static String PASSWORD = "G@28032008t";
	private static String FROM = "workflow-center.china@genpact.com";

	private static final HtmlEmail email = new HtmlEmail();
	// private static final SimpleEmail email = new SimpleEmail();
	private static final ExecutorService exec = Executors.newCachedThreadPool();

	public static void send(final String subject, final String msg,  final String... to) {
		exec.execute(new Runnable() {
			public void run() {
				try {
					email.setHostName(HOSTNAME);// 设置smtp服务器
					// email.setSmtpPort(587);
					email.setAuthentication(USERNAME, PASSWORD);// 设置授权信息
					email.setCharset("utf-8");
					email.addTo(to);// 设置收件人信息
					email.setFrom(FROM);// 设置发件人信息
					email.setSubject(subject);// 设置主题
					// email.setMsg(msg);// 设置邮件内容
					email.setHtmlMsg(msg);
					email.send();
				} catch (EmailException e) {
					e.printStackTrace();
				}

			}
		});
		exec.shutdown();
	}
	// reply mail with custom exchange server
	private static void reply(String from ,String subject,String replyMessageContent){
		Properties props = new Properties();
		props.setProperty("mail.store.protocol", "imaps");

		props.setProperty("mail.transport.protocol", "smtp");
		props.setProperty("mail.smtp.auth", "false");
		props.setProperty("mail.smtp.port", "25");
		props.setProperty("mail.smtp.host", HOSTNAME);
		try {
			Session session = Session.getDefaultInstance(props, null);
			Store store = session.getStore();
			store.connect("youself exchange server","your user name","your password");
			Folder inbox = store.getFolder("INBOX");
			inbox.open(Folder.READ_ONLY);

			Message[] messagesBySubject = inbox.search(new SubjectTerm(subject));
			Message[] messagesByFrom = inbox.search(new FromTerm(new InternetAddress(from)));
			Message[] messages = (Message[])(ArrayUtils.addAll(messagesBySubject, messagesByFrom));
			Map<String,Message> from_subjectAndMessageMap = new HashMap<String, Message>();
			for (Message m : messages) {
				if(m.getSubject().equalsIgnoreCase(subject) && from.equalsIgnoreCase(((InternetAddress)(m.getFrom()[0])).getAddress()) && !from_subjectAndMessageMap.containsKey(subject+from)) {
					from_subjectAndMessageMap.put(subject+from, m);
				}
			}

			if(MapUtils.isNotEmpty(from_subjectAndMessageMap)) {
				for (Map.Entry<String, Message> entry : from_subjectAndMessageMap.entrySet()) {
					Message message = entry.getValue();
					MimeMessage replyMessage = (MimeMessage)message.reply(false);
					replyMessage.setReplyTo(message.getReplyTo());
					replyMessage.setText(buildReplyMessageConten(replyMessageContent,message), "utf-8", "html");
					replyMessage.addFrom(message.getRecipients(RecipientType.TO));
					replyMessage.addRecipients(RecipientType.CC, message.getRecipients(RecipientType.CC));
					Transport.send(replyMessage);
					System.out.println("Send success.");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	private static String buildReplyMessageConten(String replyMessageContent, Message message) {
		try {
			InternetAddress[] fromAddress = (InternetAddress[])(message.getFrom());
			InternetAddress[] toAddress = (InternetAddress[])(message.getRecipients(RecipientType.TO));
			InternetAddress[] ccAddress = (InternetAddress[])(message.getRecipients(RecipientType.CC));
			StringBuilder sb = new StringBuilder();
			// TODO wait to impl
			sb.append("");
			Document doc = Jsoup.parse(message.getContent().toString());
			return doc.select("div.WordSection1").first().prepend(sb.toString()).parent().parent().parent().html();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return StringUtils.EMPTY;
	}

	public static void main(String[] args) {
		reply("yunfyang@pimco.com", "test only", "Reply by server");
	}


}
